<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryRef" :inline="true" label-width="120px" v-show="showSearch">

			<el-form-item label="省" prop="province">
				<el-select v-model="queryParams.province" :disabled="!isAdmin" placeholder="请选择省" @change="chooseProvince" clearable>
					<el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="市" prop="city">
				<el-select v-model="queryParams.city" placeholder="请选择市" @change="chooseCity" clearable>
					<el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item">
					</el-option>
				</el-select>
			</el-form-item>
			<!--<el-form-item label="区/县" prop="countyId">
				<el-select v-model="queryParams.countyId" placeholder="请选择区/县" clearable>
					<el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
					</el-option>
				</el-select>
			</el-form-item>-->

			<el-form-item style="margin-left: 40px;">
				<el-button type="primary" @click="handleQuery">查询</el-button>
				<el-button @click="resetQuery">重置</el-button>
				<el-button type="primary" icon="Edit"  @click="handleExport">导出</el-button>
			</el-form-item>
		</el-form>
		<!--<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" icon="Plus" @click="handleAdd">添加</el-button>
			</el-col>

		</el-row>-->

		<el-table v-loading="loading" ref="tableRef" :data="dataList" stripe @selection-change="handleSelectionChange" row-key="id">

			<el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
			<el-table-column label="省" align="center" prop="province" />
			<el-table-column label="市" align="center" prop="city" />
			<!--<el-table-column label="区（县）" align="center" prop="projectCompleteInstitution" />
			<el-table-column label="月份" align="center" prop="projectCompleteDate" />-->
			<el-table-column label="年平均降水量" align="center" prop="avPrec" />
			<el-table-column label="年最高降水量" align="center" prop="hPrec" />
			<el-table-column label="年最低降水量" align="center" prop="lPrec" />
			<el-table-column label="操作" align="center" width="210" class-name="small-padding fixed-width">
				<template #default="scope">
					<el-button type="text" @click="handleView(scope.row)">查看</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows" @pagination="getList" />

		<!-- 查看 -->
		<el-dialog v-model="open" width="1000px" title="查看气象数据" append-to-body :show-close="false" :close-on-click-modal="false">
			<p></p>
			<el-form ref="ruleForm" :model="form" :rules="rules" label-width="160px">
				<el-row>
					<el-col :span="8">
						<el-form-item label="省" prop="province">
							<span>{{form.province}}</span>
							
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="市" prop="city">
							<span>{{form.city}}</span>
						</el-form-item>
					</el-col>
					<el-col :span="8">
					</el-col>
				</el-row>
				<!--<el-row>
					<el-col :span="12">
						<el-form-item label="区/县" prop="county">
							<span>{{form.county}}</span>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="月份" prop="month">
							<span>{{form.month}}</span>
						</el-form-item>
					</el-col>
				</el-row>-->
				<el-row>
					<el-col :span="8">
						<el-form-item label="年平均降水量(毫米)" prop="avPrec">
							<span>{{form.avPrec}}</span>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="年最高降水量(毫米)" prop="hPrec">
							<span>{{form.hPrec}}</span>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="年最高降水量日期" prop="hPrecDate">
							<span>{{form.hPrecDate}}</span>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="8">
						<el-form-item label="年最低降水量(毫米)" prop="lPrec">
							<span>{{form.lPrec}}</span>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="年最低降水量日期" prop="lPrecDat">
							<span>{{form.lPrecDat}}</span>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="年平均温度(摄氏度)" prop="avTemp">
							<span>{{form.avTemp}}</span>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="8">
						<el-form-item label="年最高温度(摄氏度)" prop="hTemp">
							<span>{{form.hTemp}}</span>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="年最高温度日期" prop="hTempDate">
							<span>{{form.hTempDate}}</span>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="年最低温度(摄氏度)" prop="lTemp">
							<span>{{form.lTemp}}</span>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="8">
						<el-form-item label="年最低温度日期" prop="lTempDate">
							<span>{{form.lTempDate}}</span>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="年平均风向" prop="avWinddir">
							<span>{{form.avWinddir}}</span>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="年平均风力" prop="avWindgrade">
							<span>{{form.avWindgrade}}</span>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			
			<template #footer>
				<div class="dialog-footer">
					<!--<el-button type="primary" v-if="form.banben == '保存新版本'" @click="submitForm">保存</el-button>
          <el-button type="primary" v-else @click="overSave">保存</el-button>-->
					<!-- <el-button type="primary" @click="clearForm">清空</el-button> -->
					<el-button @click="closeForm">取消</el-button>
				</div>
			</template>
		</el-dialog>

		<el-dialog v-model="openDoc" width="800px" title="数据说明" append-to-body>
			<p class="mt15"></p>
			<p>数据类别【{{ dataType }}】应上传符合以下字段的shp文件</p>
			<el-table :data="docList" stripe>
				<el-table-column label="序号" align="center" type="index" width="80" />
				<el-table-column label="数据名称" align="center" prop="dataName" />
				<el-table-column label="数据类别" align="center" prop="dataType" />
				<el-table-column label="是否必填" align="center" prop="isMust" />
				<el-table-column label="数据说明" align="center" prop="dataDesc" width="200" show-overflow-tooltip />
			</el-table>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="openDoc = false">关闭</el-button>
				</div>
			</template>
		</el-dialog>

	</div>
</template>

<script setup name="climateData">
	import { getUserId } from '@/utils/auth'
	import { getProvince, getChildArea } from "@/api/system/division";
	// import { getPermission } from "@/api/resultsReportImg/imgQuery.js"
	import { getAdmin } from '@/api/datamanage/sysData/administrativeArea.js';
	import { ElMessageBox } from 'element-plus'
	import { listClimateData, updateAdministrativeArea, getDetail, delAdministrativeArea, dataVersionIsUseForDel, getDataTyes, getChildDataType, isExistData, dataVersionIsUse, getDataDoc, getVersionCode } from '@/api/datamanage/climateData'
	const {
		proxy
	} = getCurrentInstance();
	const isAdmin = ref(true);
	const activeName = ref('Y02');
	const router = useRouter();
	const dataList = ref([]);
	const dataListY04 = ref([]);
	const dataListY05 = ref([]);
	const dataListY06 = ref([]);
	const dataListY10 = ref([]);
	const ids = ref([]);
	const loading = ref(false);
	const single = ref(true);
	const multiple = ref(true);
	const total = ref(0);
	const showSearch = ref(true);
	const openDoc = ref(false);
	const optionData = ref([]);
	const optionData1 = ref([]);
	const optionData2 = ref([]);
	const optionData3 = ref([]);
	const provinceData = ref([]); //省
	const cityData = ref([]); //市
	const areaData = ref([]); //区、县
	const provinceFormData = ref([]); //省
	const cityFormData = ref([]); //市
	const areaFormData = ref([]); //区、县
	const provinceFormData1 = ref([]); //省
	const cityFormData1 = ref([]); //市
	const areaFormData1 = ref([]); //区、县
	const open = ref(false);
	const openData = ref(false);
	const docList = ref([]);
	const dataType = ref('');
	const selectData = ref([]);

	const isSpatialData = ref(2);
	const name = ref(null);
	const isHasFile = ref(0);
	const fileType = ref([]);
	const code = ref(null);

	const openMessage = ref(false);
	const tipMsg = ref('');

	const versionCodeList = ref([]);

	const isFirstOpen = ref(true);

	const coverData = ref({});

	const provinceIdCheck = (rule, value, callback) => {
		if(!value && form.value.dataRangeCountry == 2) {
			callback(new Error('请选择省'))
		} else if(value == undefined && form.value.dataRangeCountry == undefined) {
			callback()
		} else {
			callback()
		}
	}

	const data = reactive({
		queryParams: {
			page: 1,
			rows: 10,
			province: '',
			city: '',
		},
		form:{},
		formY02: {
			
		},
		formY04: {
			
		},
		formY05: {
			
		},
		formY06: {
			
		},
		formY10: {
			
		},
		formData: {
			dataScope: '1',
			type: '1',
		},
		rules: {
			dataRangeCountry: [{
				required: true,
				message: "范围不能为空",
				trigger: "change"
			}],
			provinceId: [{
				message: "省不能为空",
				trigger: "change",
				validator: provinceIdCheck
			}],
			dataType: [{
				required: true,
				message: "数据类别不能为空",
				trigger: "change"
			}],
			dataType2: [{
				required: true,
				message: "子数据类别不能为空",
				trigger: "change"
			}],
			dataName: [{
				required: true,
				message: "数据名称不能为空",
				trigger: "blur"
			}],
			dataDesc: [{
				required: true,
				message: "数据说明不能为空",
				trigger: "blur"
			}],
			versionCode: [{
				required: true,
				message: "版本号不能为空",
				trigger: "change"
			}],
			versionTime: [{
				required: true,
				message: "版本日期不能为空",
				trigger: "change"
			}],
			versionDesc: [{
				required: true,
				message: "版本说明不能为空",
				trigger: "blur"
			}],
			updateDesc: [{
				required: true,
				message: "更新说明不能为空",
				trigger: "blur"
			}],
			dataFileIds: [{
				required: true,
				message: "数据文件不能为空",
				trigger: "blur"
			}],
			dataFrom: [{
				required: true,
				message: "数据来源不能为空",
				trigger: "blur"
			}],
			uploadSource: [{
				required: true,
				message: "数据来源不能为空",
				trigger: "blur"
			}],
			spatialDataType: [{
				required: true,
				message: "空间数据类型不能为空",
				trigger: "blur"
			}],
			projectionInfo: [{
				required: true,
				message: "投影信息不能为空",
				trigger: "blur"
			}],
			fieldNum: [{
				required: true,
				message: "字段个数不能为空",
				trigger: "blur"
			}, {
				pattern: /^[1-9]\d*$/,
				message: '请输入大于0的整数！',
				trigger: 'change'
			}],
			fieldEntry: [{
				required: true,
				message: "字段条目不能为空",
				trigger: "blur"
			}, {
				pattern: /^[1-9]\d*$/,
				message: '请输入大于0的整数！',
				trigger: 'change'
			}],
		}
	})
	const {
		queryParams,
		form,
		formY02,
		formY04,
		formY05,
		formY06,
		formY010,
		rules,
		formData
	} = toRefs(data);

	watch(form.value, (value) => {
		// console.log(form.value.dataType2, '子数据');
		if(form.value.dataType2 && form.value.dataType2 != '') {
			optionData3.value.forEach(item => {
				if(item.dictItemId == value.dataType2) {
					isSpatialData.value = item.isSpatialData;
					name.value = item.templateFileName;
					isHasFile.value = item.isHasFile;
					code.value = item.dictItemCode;
					isSpatialData.value == 1 ? fileType.value = [] : fileType.value = ['xlsx', 'xls'];

				}
			})
		} else {
			name.value = null;
			isSpatialData.value = 2;
			isHasFile.value = 0;
			fileType.value = [];
			code.value = null;
		}
	})

	/*切换标签页*/
	function handleClick(tab, event) {
		console.log(tab.props.name);
		if(tab.props.name == "Y02") {
			//upload.url = import.meta.env.VITE_APP_BASE_API + "/result/uploadPrefectureResult"
		} else {
			//upload.url = import.meta.env.VITE_APP_BASE_API + "/result/uploadResult"
		}
	}

	// 确认上传数据文件
	function uploadFile(value) {
		if(value.list) {
			form.value.tempVersionCode = value.tempVersionCode;
			let arr = [];
			value.list.forEach(item => {
				arr.push(item.attachId)
			})
			form.value.dataFileIds = arr.join(',');
		} else {
			form.value.tempVersionCode = null;
			form.value.dataFileIds = '';
		}
	}

	function dels(value) {
		form.value.tempVersionCode = null;
		form.value.dataFileIds = '';
		form.value.dataFileId = [];
	}

	// 去数据视图
	function toView() {
		console.log(ids.value.length);
		const flag = ids.value.length == 1
		if(flag) {
			router.push({
				path: '/essentialData/dataView',
				query: {
					versionCode: selectData.value[0].versionCode,
					typeCode: selectData.value[0].dataTypeLevel3Code
				}
			})
		} else {
			ElMessageBox.alert('请勾选一条版本数据进行查看。', '消息提示', {
				confirmButtonText: '确认',
				type: 'warning'
			})
		}
	}
	// 获取版本号
	function getVersionCodes() {
		getVersionCode('xzqhsj').then(res => {
			versionCodeList.value = res.data;
		})
	}
	// 获取数据类别
	function getType() {
		getDataTyes('xzqhsj').then(res => {
			optionData1.value = res.data;
			optionData.value = [{
				dictItemId: '',
				dictItemName: '全部'
			}, ...res.data];
		})
	}

	// 下载文件
	function handleDownload(row) {
		var query = {
			attachId: row.id,
			name: row.name
		}
		location.href =
			import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(query.attachId);
	}
	// 打开字段说明
	function handleDoc() {
		getDataDoc(form.value.dataType2).then(res => {
			docList.value = res.data.list;
			dataType.value = res.data.name;
			openDoc.value = true;
		}).catch(_ => {
			docList.value = [];
			dataType.value = '';
			openDoc.value = false;
		})
	}
	// 重置数据
	function reset() {
		proxy.resetForm("ruleForm");
	}
	//添加
	function handleAdd() {
		open.value = true;
		reset();
		form.value.uploadTime = getNowFormatTime();
		form.value.uploadUser = getUserId();
		form.value.user = localStorage.getItem('userName');
		form.value.tempVersionCode = null;
		form.value.dataFileId = [];
		form.value.attachmentId = [];
	}
	//查看
	function handleView(row) {
		open.value = true;
		getDetail({id:row.jcId,typeCode:"qh"}).then(res => {
			console.log(res.data)
			form.value = res.data.data
//			formY02.value = res.data["2"];
//			dataListY04.value = res.data["4"];
//			dataListY05.value = res.data["5"];
//			dataListY06.value = res.data["6"];
//			dataListY10.value = res.data["10"];
			
		})
	}

	// 判断是系统数据是否存在
	function isExist() {
		const query = {
			countyId: form.value.countyId,
			cityId: form.value.cityId,
			dataRangeCountry: form.value.dataRangeCountry,
			provinceId: form.value.provinceId,
			dataTypeLevel3: form.value.dataType2,
		}
		isExistData(query).then(res => {
			open.value = false;
			if(res.data.isExist) {
				coverData.value = {};
				openMessage.value = true;
				tipMsg.value = res.data.tipMsg;
				coverData.value = form.value;
			} else {
				saveData()
			}
		})
	}

	function changeBanben(value) {
		form.value.versionCode = '';
		if(value == '覆盖旧版本') {
			form.value.updateDesc = '';
		}
	}
	// 判断后的保存
	function saveData() {
		const query = {
			...form.value,
			dataTypeLevel1Code: 'xzqhsj',
			dataTypeLevel2: form.value.dataType,
			dataTypeLevel3: form.value.dataType2,
		}
		uploadAdministrativeArea(query).then(res => {
			getList();
			openMessage.value = false;
			ElMessageBox.alert(`添加成功，版本号为${res.data}，请完善【元数据信息】。`, '消息', {
				confirmButtonText: '确定',
				showClose: false,
				callback: () => {
					open.value = false;
					isFirstOpen.value = true;
					handleDetail(res.data)
				},
			})
		})
	}
	// 覆盖旧版本
	function oldcOver() {
		openMessage.value = true;
		open.value = true;
		form.value.banben = '覆盖旧版本';
	}


	// 清空
	// function clearForm () {
	//     form.value.dataRangeCountry = '';
	//     form.value.provinceId = '';
	//     form.value.cityId = '';
	//     form.value.countyId = '';
	//     form.value.dataType = '';
	//     form.value.dataType2 = '';
	//     form.value.dataName = '';
	//     form.value.dataDesc = '';
	//     form.value.versionCode = '';
	//     form.value.versionTime = '';
	//     form.value.versionDesc = '';
	//     form.value.updateDesc = '';
	//     form.value.dataFileId = [];
	//     form.value.dataFileIds = '';
	//     form.value.attachmentId = [];
	//     form.value.attachmentIds = '';
	//     proxy.resetForm("ruleForm");
	// }

	// 关闭
	function closeForm() {
		open.value = false;
	}
	// 更多数据
	function handleMore(row) {
		proxy.$refs['tableRef'].toggleRowExpansion(row);
	}

	// 数据详情
	function handleDetail(versionCode) {
		getDetail(versionCode).then(res => {
			formData.value = {
				dataScope: '1',
				type: '1',
				...res.data,
			};
			editProvinceFormData(formData.value.provinceId, formData.value.cityId)
		})
	}

	/** 导出按钮操作 */
	function handleExport() {
		proxy.download('/drill/dataExport', {
    ...queryParams.value
  	},`气候数据${new Date().getTime()}.xls`)
	}


	/** 搜索按钮操作 */
	function handleQuery() {
		queryParams.value.page = 1;
		getList();
	}

	/** 重置按钮操作 */
	function resetQuery() {
		queryParams.value = {},
		dataList.value = [];
		cityData.value = [];
		proxy.resetForm("queryRef");
		queryParams.value.page = 1;
		getPermissionData();
	}

	/** 查询数据列表 */
	function getList() {
		loading.value = true;
		listClimateData({ ...queryParams.value
		}).then(response => {
			dataList.value = response.data.list ? response.data.list : [];
			total.value = response.data.total;
			loading.value = false;
		}).catch(err=>{loading.value = false;});
	}

	// 多选框选中数据
	function handleSelectionChange(selection) {
		ids.value = selection.map(item => item.id);
		single.value = selection.length != 1;
		multiple.value = !selection.length;
		selectData.value = selection;
	}

	//获取当前日期，格式YYYY-MM-DD
	function getNowFormatTime(nowDate) {
		var char = "-";
		if(nowDate == null) {
			nowDate = new Date();
		}
		var day = nowDate.getDate();
		var month = nowDate.getMonth() + 1; //注意月份需要+1
		var year = nowDate.getFullYear();
		//补全0，并拼接
		return year + char + completeDate(month) + char + completeDate(day);
	}
	//获取当前时间，格式YYYY-MM-DD HH:mm:ss
	// function getNowFormatTime() {
	//     var nowDate = new Date();
	//     var colon = ":";
	//     var h = nowDate.getHours();
	//     var m = nowDate.getMinutes();
	//     var s = nowDate.getSeconds();
	//     //补全0，并拼接
	//     return getNowFormatDay(nowDate) + " " + completeDate(h) + colon + completeDate(m) + colon + completeDate(s);
	// }
	//补全0
	function completeDate(value) {
		return value < 10 ? "0" + value : value;
	}
	// 获取子数据类别
	function chooseType(value) {
		queryParams.value.dataType2 = '';
		if(value == '') {
			optionData2.value = [];
		} else {
			optionData1.value.forEach(item => {
				if(value == item.dictItemId) {
					getChildDataType(item.dictItemCode).then(res => {
						optionData2.value = res.data;
					})
				}
			})
		}
	}

	// 获取子数据类别
	function chooseChildType(value) {
		form.value.dataType2 = '';
		if(value == '') {
			optionData3.value = [];
		} else {
			optionData1.value.forEach(item => {
				if(value == item.dictItemId) {
					getChildDataType(item.dictItemCode).then(res => {
						optionData3.value = res.data;
					})
				}
			})
		}
	}

	function chooseScope(value) {
		queryParams.value.provinceId = null;
		queryParams.value.cityId = null;
		queryParams.value.countyId = null;
	}

	function chooseFormScope(value) {
		form.value.provinceId = null;
		form.value.cityId = null;
		form.value.countyId = null;
		proxy.$refs['ruleForm'].validateField(['provinceId']);
	}

	function chooseProvince(value) {
		queryParams.value.province = value.name;
		queryParams.value.city = null;
		queryParams.value.county = null;
		cityData.value = [];
		getChildArea(value.id).then(response => {
			cityData.value = response.data;
		});
	}

	function chooseCity(value) {
		queryParams.value.city = value.name;
		queryParams.value.county = null;
		areaData.value = [];
		getChildArea(value.id).then((response) => {
			areaData.value = response.data;
		});
	}

	function chooseFormCity(value) {
		form.value.countyId = null;
		areaFormData.value = [];
		getChildArea(value).then((response) => {
			areaFormData.value = response.data;
		});
	}

	function chooseFormProvince(value) {
		form.value.cityId = null;
		form.value.countyId = null;
		cityFormData.value = [];
		getChildArea(value).then(response => {
			cityFormData.value = response.data;
		});
	}

	/** 获取省列表 */
	function getProvinceData() {
		getProvince().then(response => {
			provinceData.value = response.data;
			provinceFormData.value = response.data;
			provinceFormData1.value = response.data;
			getPermissionData()
		});
	}

	function editProvinceFormData(provinceId, cityId) {
		if(!provinceId && !cityId) {
			cityFormData1.value = [];
			areaFormData1.value = [];
		}
		if(provinceId && !cityId) {
			getChildArea(provinceId).then(response => {
				cityFormData1.value = response.data;
				areaFormData1.value = [];
			});
		}
		if(provinceId && cityId) {
			getChildArea(provinceId).then(response => {
				cityFormData1.value = response.data;
			});
			getChildArea(cityId).then(response => {
				areaFormData1.value = response.data;
			});
		}
		openData.value = true;
		proxy.resetForm("ruleFormData");
	}

	function getPermissionData(){
	const userId = getUserId()
	getAdmin({userId:userId}).then(res=>{
        isAdmin.value = res.data.isCountry;
        // 如果是国家级人员
        if(isAdmin.value){
            queryParams.value.province = '';
        }else{
			let query = {
				id:res.data.provinceId,
				name:provinceData.value.find(item=>item.id==res.data.provinceId).name
			}
			chooseProvince(query)
            queryParams.value.province = query.name;
        }
        getList();
    });
}

getProvinceData()
</script>

<style lang="scss" scoped>
	.expandTable {
		padding: 5px 20px 5px 105px;
		h3 {
			font-weight: bold;
		}
		p {
			margin: 0px;
			line-height: 25px !important;
		}
	}
	
	.tab-title {
		font-size: 16px;
		font-weight: bold;
		border-left: 4px solid #0D9AFF;
		font-family: PingFangSC-Medium;
		padding-left: 10px;
		margin-bottom: 20px;
	}
	
	:deep(.el-drawer__header) {
		margin-bottom: 0px !important;
	}
	
	.el-form--inline .el-form-item {
		margin-right: 0px!important;
	}
	
	.spanStyle {
		display: inline-block;
		width: 40px;
		text-align: center;
	}
	
	:deep(.el-table__expand-icon) {
		display: none;
	}
	
	:deep(.el-table thead.is-group th.el-table__cell) {
		border-right: 1px solid #FFFFFF !important;
		border-bottom: 1px solid #FFFFFF !important;
	}
	
	table td {
		border: 1px solid #c6c6c6;
	}
	
	table th {
		border: 1px solid #c6c6c6;
	}
</style>